package service

import (
	"context"
	"log"
	"nearby/biz/dal/db/po"
	"nearby/biz/dal/db/repo"
	"nearby/biz/domain/entity"
)

type MomentService struct {
}

type GetMomentsRequest struct {
	ViewerID int64 `json:"user_id"` // 查看者的用户id
	Limit    int64 `json:"limit"`
	Offset   int64 `json:"offset"`
}

type GetMomentsResponse struct {
	Moments []*entity.Moment `json:"moments"`
	Total   int64            `json:"total"`
}

func (ss *MomentService) GetMoments(ctx context.Context, req GetMomentsRequest) (*GetMomentsResponse, error) {
	momentRepo := repo.NewMomentRepo(ctx)
	momentPos, total, err := momentRepo.GetMoments(ctx, repo.GetMomentsRequest{
		Limit:  req.Limit,
		Offset: req.Offset,
	})
	if err != nil {
		return nil, err
	}
	momentEntities, _ := ss.ToEntities(ctx, momentPos)

	return &GetMomentsResponse{
		Moments: momentEntities,
		Total:   total,
	}, nil
}

func (ss *MomentService) ToEntities(ctx context.Context, pos []*po.Moment) ([]*entity.Moment, error) {
	momentEntities := make([]*entity.Moment, 0)
	for i := range pos {
		momentEntity, err := entity.NewMomentEntityByPo(ctx, pos[i])
		if err != nil {
			log.Printf("entity.NewMomentEntityByPo fail, err: %+v", err)
			continue
		}
		momentEntities = append(momentEntities, momentEntity)
	}
	return momentEntities, nil
}
